<template>
  <tm-app ref="app">
    <!-- 菜单层 -->

    <scroll-view class="scroll-box" scroll-y @scrolltolower="getData()">
      <view class="M0" v-if="ListState.list.length===0">
        <tm-result :showBtn="false" subTitle="收货地址空空如也 赶快添加一个吧!" title=" "/>
      </view>
      <view class="M1" v-else>
        <tm-card v-for="(item) in ListState.list" :key="item.id" :status="item.dfFlag?'默认地址':''"
                 :title="item.name+'('+item.mobile+')'" :content="item.fullAddress">
          <template v-slot:action>
            <view class="flex flex-row flex-row-center-end flex-1">
              <tm-button size="small" :round="12" color="white" :margin="[12, 0]" @click="ModalCtr.open(item,1)" label="删除" :font-size="24" :width="100"/>
              <tm-button v-if="!item.dfFlag" size="small" @click="ModalCtr.open(item,2)" :round="12" label="设为默认" :font-size="24" :width="140"/>
            </view>
          </template>
        </tm-card>

        <uni-load-more :status="ListState.moreState"/>
      </view>
    </scroll-view>


    <view class="M2">
      <tm-button :round="8" icon="tmicon-plus" block label="新建收货地址" @click="EditCtr.Open()"/>
    </view>

    <tm-float-button @click="getFromWeixin()" :width="140" :height="140" position="br" :offset="[24, 120]" :btn="{ icon: 'tmicon-weixin', color: 'green', label: '微信导入' }"/>

    <AddressWindow v-if="EditCtr.Show" :Record="EditCtr.Record" @Close="EditCtr.Close"/>


    <!--    设置默认地址弹窗-->
    <tm-modal v-model:show="ModalCtr.show" splitBtn :height="340" :title="ModalCtr.title"
              :okText="ModalCtr.okText" :content="ModalCtr.content" @ok="ModalCtr.submit()"/>
    <tm-message ref="msgRef" :lines="2"></tm-message>
  </tm-app>
</template>

<script lang="ts" setup>
import {reactive, ref} from 'vue';

import AddressWindow from '@/components/address-edit/index.vue';
import {onLoad} from "@dcloudio/uni-app";
import TmMessage from '@/tmui/components/tm-message/tm-message.vue'
import wx from "weixin-js-sdk-ts";
import {WxmpUtil} from "@/utils";
import {delAddress, getAddress, setDefaultAddr, addAddress} from '@/apis'
import UniLoadMore from "@/components/uni-load-more/uni-load-more.vue";

const msgRef = ref<InstanceType<typeof TmMessage> | null>(null)

interface record {
  id: string | number,
  name?: any;
  mobile?: any;
}

const wxAddress = ref({})

const EditCtr = reactive({
  Show: false,
  Record: {},
  Open: (data = {}) => {
    EditCtr.Show = true;
    EditCtr.Record = data;
  },
  Close: (e: any) => {
    EditCtr.Show = false;
    if (typeof e === 'object') reload()
  }
});

const ListState = reactive({
  list: [],
  hasNext: true,
  pageSize: 10,
  pageNo: 0,
  moreState: 'more',
})
//加载数据
const getData = async () => {

  if (['noMore', 'loading'].includes(ListState.moreState)) return
  ListState.moreState = "loading"
  ListState.pageNo++
  const {data} = await getAddress({pageSize: ListState.pageSize, pageNo: ListState.pageNo})
  // @ts-ignore
  ListState.list.push(...data.records)


  if (data.hasNext) {
    ListState.hasNext = data.hasNext
    ListState.moreState = "more"
  } else {
    ListState.moreState = "noMore"
  }

}

//重载数据
const reload = async () => {
  ListState.moreState = 'more'
  ListState.pageNo = 0
  ListState.list = []
  await getData()
}

const ModalCtr = reactive({
  title: '操作提示',
  content: '',
  okText: '确定',
  record: {} as record | object,
  action: 0,   //0= 初始化  1 = 删除 2= 设置默认地址
  show: false,
  reset: () => {
    ModalCtr.record = {}
    ModalCtr.action = 0
    ModalCtr.content = ''
    ModalCtr.show = false

  },

  open: (record: record, action: number) => {
    ModalCtr.reset()
    if (action === 1) ModalCtr.content = `确定要将【${record.name}-${record.mobile}】删除吗?`
    if (action === 2) ModalCtr.content = `确定要将【${record.name}-${record.mobile}】置成默认的收货地址吗?`

    ModalCtr.action = action
    ModalCtr.record = record
    ModalCtr.show = true


  },
  submit: async () => {


    console.log(ModalCtr.action)
    if (ModalCtr.action === 1) {

      const {id} = ModalCtr.record
      await delAddress(id)

      ListState.list = ListState.list.filter(x => x.id !== id);
      msgRef.value.show({model: 'success', title: '地址删除成功！', duration: 1500})

    }
    if (ModalCtr.action === 2) {

      await setDefaultAddr(ModalCtr.record.id)
      await reload()

      msgRef.value.show({model: 'success', title: '默认地址设置成功！', duration: 1500})

    }

  }
})


const getFromWeixin = async () => {
  console.log("加载数据。。")

  const wxConfigData = await WxmpUtil.getWxConfigData(['openAddress'])
  console.log("微信配置参数", wxConfigData)
  // @ts-ignore
  wx.config(wxConfigData)
  wx.openAddress({
    success: async (res) => {
      const mobile = res.telNumber;
      const name = res.userName;
      const province = res.provinceName;
      const city = res.cityName;
      const district = res.countryName;
      const address = res.detailInfo;
      const fullAddress = province + city + district + address
      const putData = {mobile, name, province, city, district, address, fullAddress ,dfFlag:false}
      const {code,message } = await addAddress(putData)
      alert(message)
    if (code===0){
     await reload()
    }else{
      msgRef.value.show({model: 'error', title: '微信地址添加失败！', duration: 1500})
    }

    }

  });

}
onLoad(async () => {
  await WxmpUtil.wxAuthorize()
  await getData()

})

</script>

<style lang="less" scoped>

.scroll-box {
  height: 100vh;

  .M1 {
    width: 100%;
    margin-top: 24rpx;
    padding-bottom: 100px;
  }

}

.M2 {
  width: 100%;

  position: fixed;
  bottom: 0;
  left: 0;
  padding: 0 24rpx;
  box-sizing: border-box;
}
</style>
